dojo.provide("miaigo.view.BoardView");

dojo.require("miaigo.view.BaseView");
dojo.require("miaigo.view.board.Board");

dojo.declare(
    "miaigo.view.BoardView",
    [miaigo.view.BaseView, dijit._Templated],
    {
	templateString: "<div dojoAttachPoint='containerNode'></div>",

	_connDefs:
	{
	    inbound:
	    [
		{ event: "onCurrentMoveChanged", method: "onMove"}
	    ]
	},

	_board: null,

	// boardAlign: String (center|left|right)
	//     alignment of the board in this view
	boardAlign: "center",

	postCreate: function()
	{
	    this.inherited(arguments);

	    this._board = new miaigo.view.board.Board();
	    this._board.stoneSize = 32;
	    this._board.boardMargin = 24;
	    this.containerNode.appendChild(this._board.domNode);
	},

	startup: function()
	{
	    if (this._started)
		return;

	    this.inherited(arguments);

	    if (this._board)
	    {
		this._board.startup();
		dojo.attr(this._board.domNode, "align", this.boardAlign);
	    }
	},

	setStoneSize: function(size)
	{
	    this._board.setStoneSize(size);
	},

	resize: function(changeSize, resultSize)
	{
	    console.debug(resultSize);
	    this.inherited(arguments);

	    // calculate board size to fit
	    if (resultSize && resultSize.w && resultSize.h)
	    {
		var boardSize = Math.min(resultSize.w, resultSize.h);
		var stoneSize = Math.round(boardSize / (19+1));

		if (stoneSize < 20)
		    stoneSize = 20;
		if (stoneSize > 48)
		    stoneSize = 48;
		this._board.setStoneSize(stoneSize);
	    }
	},

	setBoardState: function(/* miaigo.model.BoardState */ state)
	{
	    this._board.clearBoard();

	    if (state)
	    {
		dojo.forEach
		(
		    state.getAllBlocks(),
		    function(block)
		    {
			this._board.placeStoneBlock(block);
		    },
		    this
		);
	    }
	},

	onMove: function(/* miaigo.model.Move */move)
	{
	    if (move)
	    {
		this.setBoardState(move.getBoardState());
	    }
	}
    });